#!/usr/bin/python
# -*- coding: utf-8 -*-

#from numpy import *
from pylab import *


source_file = 'EURUSD_1_2012-12-01_2013-12-01.csv'
source_file = 'EURUSD_1_2011-12-01_2012-12-01.csv'

#-------------------------------------------------------------------------------
def load_cost_data(cost_file):
    print 'Load data from',cost_file
    lines = [ x.strip().split(',') for x in open(cost_file, 'r').readlines() ]
    data={}
    for bar in lines:
        date,time,copen,max,min,cclose,vol = bar
        if date not in data: data[date]={}
        data[date][time]=(float(copen),float(max),float(min),float(cclose),float(vol))

    def create_times():
        r = []
        for i in xrange(0,24):
            for j in xrange(0,60,1):
                r.append( '%02i'%i+':'+'%02i'%j )
        return r
    times = create_times()

    sorted_dates = sorted([x for x in data])
    sorted_times = sorted(times)

    def get_prev_bar(date,time):
        dindex = sorted_dates.index(date)
        tindex = sorted_times.index(time)
        if tindex==0: return dindex-1, len(sorted_times)-1
        return dindex, tindex-1

    def contains_bar( d, date, time):
        if date not in d: return False
        return time in d[date]

    def search_cost(date,time):
        if contains_bar(data, date, time): return data[date][time]
        d,t = get_prev_bar(date,time)
        while(d>=0 and not contains_bar(data, sorted_dates[d], sorted_times[t])):
            d,t = get_prev_bar(sorted_dates[d], sorted_times[t])
        if d<0: return data.items()[0][1].items()[0][1]
        return data[sorted_dates[d]][sorted_times[t]]

    for d in sorted_dates:
        for t in sorted_times:
            data[d][t] = search_cost(d,t)

    return sorted_dates, sorted_times, data


#-------------------------------------------------------------------------------
def get_prev_bar(days, times, date, time):
    dindex = days.index(date)
    tindex = times.index(time)
    if tindex==0: return dindex-1, len(times)-1
    return dindex, tindex-1
#-------------------------------------------------------------------------------
def get_next_bar(days, times, date, time):
    dindex = days.index(date)
    tindex = times.index(time)
    if tindex==len(times)-1: return dindex+1, 0
    return dindex, tindex+1

days,times,data = load_cost_data(source_file)
bars = [(d,t) for d in days for t in times]

#plot( xrange(len(bars)), [data[d][t][0] for d,t in bars], 'b-' )
#show()

#-------------------------------------------------------------------------------
def derivative(cost):
    r = [0]
    for i in xrange(1, len(cost)):
        r.append( float(cost[i]) - float(cost[i-1]) )
    return r

#-------------------------------------------------------------------------------
def slot(i,n):
    return int(i/float(n))*n

#-------------------------------------------------------------------------------
def replicator(v, n):
    r=[]
    for e in v:
        r+=[e]*n
    return r

#-------------------------------------------------------------------------------
def make_same_len( v, s ):
    res = []
    for e in v:
        f = s/len(e)
        res.append( replicator( e , f ) )
        while len(res[-1])<s:
            res[-1].append(res[-1][-1])
    return res

#-------------------------------------------------------------------------------
def smooth_by_window( l,r, v ):
    def win( l,r, v, i ):
        if i+l < 0: l=-i
        if i+r >= len(v): r=len(v)-i-1
        return average(v[i+l : i+r+1])
    return [ win(l,r, v, i) for i in xrange(0,len(v)) ]
        

cost1  = [data[d][t][0] for d,t in bars]
cost5  = [cost1[i] for i in xrange(0,len(cost1),5)]
cost15 = [cost5[i] for i in xrange(0,len(cost5),3)]
cost30 = [cost5[i] for i in xrange(0,len(cost5),30/5)]
costH  = [cost5[i] for i in xrange(0,len(cost5),60/5)]
costD  = [cost5[i] for i in xrange(0,len(cost5),288)]
costW  = [costD[i] for i in xrange(0,len(costD),7)]

d_cost1  = derivative(cost1)
d_cost5  = derivative(cost5)
d_cost15 = derivative(cost15)
d_cost30 = derivative(cost30)
d_costH  = derivative(costH)
d_costD  = derivative(costD)
d_costW  = derivative(costW)

    
#-------------------------------------------------------------------------------
def all_trends_up(frames, frames_derivative, cost, t):
    for f in frames_derivative:
        if f[t]<= 0 : return -1
    return t
#-------------------------------------------------------------------------------
def all_trends_down(frames, frames_derivative, cost, t):
    for f in frames_derivative:
        if f[t]>= 0 : return -1
    return t

#-------------------------------------------------------------------------------
def all_trends_up_first_down(frames, frames_derivative, cost, t):
    if all_trends_up(frames, frames_derivative, cost, t) > 0:
        for x in xrange(t, len(cost)):
            if cost[t] > cost[x]:
                return x
    return -1   


#-------------------------------------------------------------------------------
def check_probability(frames, derivatives, cost_frame, t, condition):
    ttimes=0
    p=0; ptimes=0
    n=0; ntimes=0
    e=0; etimes=0
    is_print_failures=False
    for i in xrange( 100, len(cost_frame)-100 ):
        q = condition(frames, derivatives, cost_frame, i)
        if q > 0 and q+t<len(cost_frame):
            ttimes+=1
            if cost_frame[q]<cost_frame[q+t]:
                p += cost_frame[q+t] - cost_frame[q]
                ptimes += 1
            elif cost_frame[q]==cost_frame[q+t]:
                e += 0
                etimes += 1
            else:
                n += cost_frame[q] - cost_frame[q+t]
                ntimes += 1
                    
    return ptimes/float(ttimes), etimes/float(ttimes), ntimes/float(ttimes), p, n

#-------------------------------------------------------------------------------
def check_strategy(frames, derivatives, cost_frame, open_condition, close_condition, timer_delay = 100, profit_rate=1.01):
    open_cost=0
    stopplos_cost=0
    profit_cost=0
    total_sum=0
    state='closed'
    offset=500
    
    timer_timeout = 0
    
    stopplos_enable = True; move_stopplos = False
    profit_enable = True
    timer_enable = False
    
    
    for i in xrange(offset,len(cost_frame)-offset):
        if state=='closed':
            if open_condition(frames, derivatives, cost_frame, i):
                open_cost = cost_frame[i]
                stopplos_cost = open_cost
                profit_cost = open_cost*profit_rate
                timer_timeout = timer_delay + i
                state='open'
        else:
            if stopplos_enable:
                if move_stopplos:
                    if cost_frame[i] > stopplos_cost:
                        stopplos_cost = cost_frame[i]
                if cost_frame[i] < stopplos_cost:
                    total_sum += cost_frame[i] - open_cost
                    state = 'closed'
            if profit_enable:
                if cost_frame[i] >= profit_cost:
                    total_sum += cost_frame[i] - open_cost
                    state='closed'
            if close_condition(frames, derivatives, cost_frame, i):
                total_sum += cost_frame[i] - open_cost
                state='closed'
            if timer_enable:
                if timer_timeout <= i:
                    total_sum += cost_frame[i] - open_cost
                    state='closed'
                
    if state=='open' and open_cost < cost_frame[i] :
        total_sum += cost_frame[i] - open_cost
    
    return total_sum



def check_strategy2(frames, derivatives, cost_frame, timer_delay = 100, profit_rate=1.01):
    open_cost=0
    stopplos_cost=0
    profit_cost=0
    total_sum=0
    state='closed'
    offset=500
    
    timer_timeout = 0
    
    stopplos_enable = False; move_stopplos = False
    profit_enable = False
    timer_enable = True
    
    ts=[]
    for i in xrange(offset,len(cost_frame)-offset):
        if state=='closed':
            if all_trends_up(frames, derivatives, cost_frame, i)>0:
                open_cost = cost_frame[i]
                state='wait'
                #print 'wait',i
        elif state=='wait':
            if open_cost > cost_frame[i]:
                open_cost = cost_frame[i]
                stopplos_cost = open_cost
                profit_cost = open_cost*profit_rate
                timer_timeout = timer_delay + i
                state='open'
                #print 'open',i
        elif state=='open':
            if stopplos_enable:
                if move_stopplos:
                    if cost_frame[i] > stopplos_cost:
                        stopplos_cost = cost_frame[i]
                if cost_frame[i] < stopplos_cost:
                    total_sum += cost_frame[i] - open_cost
                    state = 'closed'
            if profit_enable:
                if cost_frame[i] >= profit_cost:
                    total_sum += cost_frame[i] - open_cost
                    state='closed'
            #if close_condition(frames, derivatives, cost_frame, i):
                #total_sum += cost_frame[i] - open_cost
                #state='closed'
            if timer_enable:
                if timer_timeout <= i:
                    total_sum += cost_frame[i] - open_cost
                    state='closed'
                    #print 'timeout',i
        ts.append(total_sum)        
    if state=='open' and open_cost < cost_frame[i] :
        total_sum += cost_frame[i] - open_cost
    
    return total_sum, ts


seria=2
if seria==1:
    work_frames = [ cost30, costH, costD, costW ]
    work_derivs = [ d_cost30, d_costH, d_costD, d_costW ]
    work_cost = cost30
elif seria==2:
    work_frames = [ cost5, cost15, costD, costW ]
    work_derivs = [ d_cost5, d_cost15, d_costD, d_costW ]
    work_cost = cost5

work_frames = make_same_len( work_frames, len(work_cost) )
work_derivs = make_same_len( work_derivs, len(work_cost) )


#===============================================================================
show_probabilities = False
show_profits = False
run_strategy = True

if show_probabilities:
    x=range(1,20)
    y=[ p+e for p,e,n,_,_ in [ check_probability(work_frames, work_derivs, work_cost, i, all_trends_up_first_down) for i in x] ]
    xlabel(u'Период ожидания (в свечках)')
    ylabel(u'Вероятность повышения цены через Х свечей')
    plot( x, y, 'b-o' )
    show()

if show_profits:
    x=range(1,50)
    y=[ p-n for _,_,_,p,n in [ check_probability(work_frames, work_derivs, work_cost, i, all_trends_up_first_down) for i in x] ]
    xlabel(u'Период ожидания (в свечках)')
    ylabel(u'Прибыль через Х свечей')
    plot( x, y, 'b-o' )
    show()

if run_strategy:
    
    def search_best_index(l,r):
        result = [ check_strategy2( [x[l:r+1] for x in work_frames], [x[l:r+1] for x in work_derivs], work_cost[l:r+1], timer_delay = x)[0] for x in range(1,50) ]
        #print average( result ), min( result ), max( result )
        return result.index(max(result))+1
    
    r = [ search_best_index(x-1000, x) for x in xrange(1000,len(work_cost)) ]
    plot( range(len(r)), r )
    show()
    
    #exit(0)

    #print 'best index',result.index(max(result))+1
    #indx = result.index(max(result))+1
    #result,ts = check_strategy2( work_frames, work_derivs, work_cost, timer_delay = indx )
    #print result
    #print min( ts ), max( ts )
    #plot( range(len(ts)), ts )
    #show()
